package com.elminster.graphic.impl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.util.List;

import com.elminster.datastruct.PriorityList;
import com.elminster.graphic.IGraphic;

import com.elminster.graphic.GraphicBase;
import com.elminster.graphic.entity.GraphicEntity;

public class PiedGraphicImpl extends GraphicBase implements IGraphic {
    
    private static final Insets insets = new Insets(5, 5, 5, 5);
    private static final Color[] colors = new Color[] {Color.blue,
        Color.cyan, Color.darkGray, Color.gray, Color.green, 
        Color.lightGray, Color.magenta, Color.orange, Color.pink, 
        Color.red, Color.yellow};

    public void draw(Graphics g) {
        if (isMerge()) {
            entity = meger();
        }
        if (null == entity || entity.isEmpty()) {
            return;
        }
        double sum = 0.0d;
        List<GraphicEntity> list = new PriorityList<GraphicEntity>();
        for (GraphicEntity e : entity) {
            sum += e.getValue();
            int idx = list.indexOf(e);
            GraphicEntity et;
            if (-1 == idx) {
                et = null;
            } else {
                et = list.remove(idx);
            }
            e.add(et);
            list.add(e);
        }
        Color originalColor = g.getColor();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
        int startAngle = 0;
        int i = 0;
        for (; i < colors.length - 1; i++) {
            g2d.setColor(colors[i]);
            GraphicEntity e = list.get(i);
            int endAngle = (int) (e.getValue() / sum * 360);
            g2d.fillArc(insets.left, insets.top, width - insets.left - insets.right,
                    height - insets.top - insets.bottom, startAngle, endAngle);
            startAngle += endAngle;
        }
        g2d.setColor(colors[i]);
        g2d.fillArc(insets.left, insets.top, width - insets.left - insets.right,
                    height - insets.top - insets.bottom, startAngle, 360 - startAngle);
        g2d.setColor(originalColor);
    }
}
